<?php

declare(strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

use think\Exception;
use think\facade\Cache;
use think\facade\Event;
use app\common\controller\Config;

/**
 * @mixin \think\Model
 */
class Relation extends Base
{

    protected $name = 'user_relation';

    public function getAll($param)
    {
        try {

            return $this->where($param)->select()->toArray();
        } catch (\Exception $e) {
            return [];
        }
    }

    protected function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,is_active,level_id,team_total');
    }

    protected function fresh()
    {
        return $this->hasOne(User::class, 'id', 'new_uid')
            ->field('id,code,photo,nickname,mobile,team_total,level_id,team_total');
    }

    public static function generate(int $new_uid, $new_code, int $parentId, string $parentCode): bool
    {
        try {
            parent::create([
                'uid'      => $parentId,
                'code'     => $parentCode,
                'algebra'  => 1,
                'new_uid'  => $new_uid,
                'new_code' => $new_code,
            ]);
            $time = time();

            parent::where('new_uid', $parentId)
                ->field('uid,code,algebra + 1 as algebra,' . $time . ' as create_time,' . $time . ' as update_time,' . $new_uid . ' as new_uid,"' . $new_code . '" as new_code')
                ->selectInsert([
                    'uid',
                    'code',
                    'algebra',
                    'create_time',
                    'update_time',
                    'new_uid',
                    'new_code',
                ], (new static())->getName());

            return true;
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @param $amount - 金额
     * @param $uid - 会员ID
     * @param string $key - 团队业绩key
     * 原点 2021年12月28日11:50:17 更新团队业绩
     */
    public static function renewTeamTotal($amount, $uid, $key = 'team_total')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($amount))->update();
        }
    }



    /**
     * @param $uid
     * @return array
     * 原点 2023年5月12日17:01:26 升级
     */
    public static function upgrade($uid): array
    {
        try {
            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();

            foreach ($list as $item) {
                $user_total = self::getUserCount($item->user->level_id, $item->user->id);
                $level = Level::where('id', '>', $item->user->level_id)
                    ->where('team_money', '<=', $item->user->team_total)
                    ->where('zt_count', '<=', $user_total)
                    ->order('id', 'asc')
                    ->find();
                if ($level) {
                    User::update(['level_id' => $level->id, 'id' => $item->uid]);
                }
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 奖金发放
     */
    public static function freeBonus($uid, $money)
    {
        $sys = Config::lists();
        try {
            $tp = 0; //直推奖
            $team_money = 0; //团队奖
            $level_money = 0; //平级奖
            /**
             * 直推奖
             */
            $user = User::where('id', $uid)->find();
            if ($user->parent_id != 0) {
                $tmoney = self::getUserMoney($user->parent_id); //判断是否有缔造积分
                if ($tmoney > 0) {
                    $tp = round($money * $sys['tp_1'], 2);
                    $data = [
                        'uid' => $uid,
                        'intro' => '直推奖',
                        'cate' => 1,
                    ];
                    $res = self::getUserMoneyMax($user['parent_id'], $tp, $data);
                }
            }
            /**
             * 团队奖
             */
            $list = self::getLevelInfo($user->id);
            // print('<pre>');print_r($list);die;
            if (!empty($list)) {
                foreach ($list as $v) {
                    $tp_2 = self::getUserMoney($v['uid']); //判断是否有缔造积分
                    if ($tp_2 > 0 && $v['bl'] > 0) {
                        $team_money_1 = round($money * $v['bl'], 2);
                        $data = [
                            'uid' => $uid,
                            'intro' => '团队奖',
                            'cate' => 2,
                        ];
                        $res = self::getUserMoneyMax($v['uid'], $team_money_1, $data);
                        $team_money += $team_money_1;
                    }
                    if ($v['pid'] != 0) {
                        $tp_3 = self::getUserMoney($v['pid']); //判断是否有缔造积分
                        if ($tp_3 > 0) {
                            $level_money_1 = round($money * $sys['tp_2'], 2);
                            $data = [
                                'uid' => $uid,
                                'intro' => '平级奖',
                                'cate' => 3,
                            ];
                            $res = self::getUserMoneyMax($v['pid'], $level_money_1, $data);
                            $level_money += $level_money_1;
                        }
                    }
                }
            }
            $toal_money = $tp + $team_money + $level_money;
            if ($toal_money > 0) {
                Event::trigger('Statistics', ['key' => 'expend', 'value' => $toal_money]);
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 获取用户团队人数/直推人数
     */
    public static function getUserCount($level, $uid)
    {

        $count = 0;
        $new_uid = parent::where(['uid' => $uid, 'algebra' => 1])->order('algebra asc')->column('new_uid');
        if ($level == 0) {
            $count = User::whereIn('id', $new_uid)->where(['is_active' => 2])->count();
        } else {
            foreach ($new_uid as $v) {
                $cnew_id = parent::where(['uid' => $v])->order('algebra asc')->column('new_uid');
                array_push($cnew_id, $v);
                $u_count = User::whereIn('id', $cnew_id)->where('level_id', '>=', $level)->where(['is_active' => 2])->count();
                if ($u_count > 0) {
                    $count += 1;
                }
            }
        }
        return  $count;
    }

    /**
     * 级差奖励
     */
    public static function getLevelInfo($uid)
    {
        try {
            $level_id = 0;
            $list = parent::where('new_uid', $uid)->with(['user'])->order('algebra asc')->select();
            foreach ($list as $k => $v) {
                if ($v->user->level_id > $level_id && $v->user->level_id < 8) {
                    $nowmoney = Level::where('id', $v->user->level_id)->value('tp_1');
                    $upmoney = Level::where('id', $level_id)->value('tp_1');
                    $data['uid'] = $v->user->id;
                    $data['bl'] = $nowmoney - $upmoney;
                    $data['pid'] = self::getLevelUser($v->user->level_id, $v->user->id);
                    // if ($data['bl'] > 0) {
                    $ids[] = $data;
                    // }
                    $level_id = $v->user->level_id;
                }
            }
            if (!empty($ids)) {
                return $ids;
            } else {
                return [];
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 获取平级用户
     */
    public static function getLevelUser($level, $uid)
    {
        try {
            $id = 0;
            $list = parent::where('new_uid', $uid)->with(['user'])->order('algebra asc')->select();
            foreach ($list as $k => $v) {
                if ($v->user->level_id == $level) {
                    return $v->user->id;
                }
            }
            return $id;
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 判断是否有缔造积分
     */
    public static function getUserMoney($uid)
    {
        $status = 0;
        $user = User::where('id', $uid)->with('assets')->find();
        $count = WholesaleOrder::where(['uid' => $uid, 'free' => 1])->count();
        if ($user->assets->bonus_2 >= 50 || $user->assets->bonus_1 > 0 || $count > 0) {
            $status = 1;
        }
        return $status;
    }
    /**
     * 判断是否封顶
     */
    public static function getUserMoneyMax($uid, $money, $account)
    {
        try {
            $user = User::where('id', $uid)->find();
            $capping = Capping::where('uid', $uid)->whereDay('create_time')->find();
            $is_pay = 1; //是否发奖
            if (empty($capping)) {
                $data = [
                    'uid' => $uid,
                    'money' => $money,
                    'time' => date('Y-m-d'),
                ];
                Capping::create($data);
                $toal_money = $money;
            } else {
                $toal = $user->capping_day - $capping->money;
                if ($user->capping_day <= $capping->money) {
                    $is_pay = 0;
                } else {
                    if ($toal >= $money) {
                        $toal_money = $money;
                    } else {
                        $toal_money = $toal;
                    }
                    $capping->money += $toal_money;
                    $capping->save();
                }
            }
            if ($is_pay  == 1 && $toal_money > 0) {
                Target::Account()->basics($uid, 'bonus_1', $toal_money, $account['intro'], '+')
                    ->createBonus($account['uid'], $account['cate']);
            }
            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
}
